import request from '../../utils/request.js'
import hasLogin from '../../utils/hasPermission.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    navList: [],
    currentNavId: '',
    videoList: [],
    refreshTriggered: false,
    lastVideoId: ''
  },


  //导航栏切换，默认选中第一个
  selectNav: async function(event) {
    //切换导航
    if (event) {
      this.setData({
        currentNavId: event.currentTarget.dataset.id
      })
      this.setData({
        videoList: []
      })
    }
    wx.showLoading({
      title: '加载中',
    })
    //根据导航栏id请求相应的视频数据
    const videoResData = await request('/video/group', {
      id: this.data.currentNavId
    })
    //要展示的数据
    const videoList = videoResData.datas.map(video => {
      const {
        vid: id,
        urlInfo,
        creator,
        description,
        commentCount,
        shareCount,
        title
      } = video.data
      return {
        id,
        title,
        description: description !== null ? description : '',
        commentCount,
        shareCount,
        videoUrl: urlInfo.url,
        avatarUrl: creator.avatarUrl,
        coverUrl: creator.avatarUrl,
        publisher: creator.nickname,
      }
    })
    this.setData({
      videoList
    })
    wx.hideLoading()
  },

  //进入页面加载导航栏对应视频数据
  getNavVideoList: async function() {
    const res = await request('/video/group/list')
    this.setData({
      navList: res.data,
      currentNavId: res.data[0].id
    })
    this.selectNav()
  },


  //下拉刷新数据
  refreshVideoList: async function() {
    this.setData({
      videoList: []
    })
    this.selectNav()
    this.setData({
      refreshTriggered: false
    })
  },

  //播放视频
  handlePlayVideo(event) {
    console.log(event)
    const videoId = event.currentTarget.id
    this.setData({
      lastVideoId: videoId
    }, () => {
      const videoContext = wx.createVideoContext(videoId, this)
      videoContext.play()
    })
  },

  

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    //有登录过才能进入该页面
    // if (hasLogin()) {
    //   this.getNavVideoList()
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function() {
    if (hasLogin()) {
      this.getNavVideoList()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function({
    from,
    target
  }) {
    if (from === 'menu') {
      return {
        title: '谷粒云音乐',
        path: 'pages/index/index',
        imageUrl: '/static/images/kof/kof-01.jpg'
      }
    } else if (from === 'button') {
      return {
        title: target.dataset.sharetitle,
        path: 'pages/video/video',
        imageUrl: target.dataset.shareimg
      }
    }
  }
})